<?php

namespace app\api\model\user;

use app\api\model\Setting as SettingModel;
use app\api\service\User as UserService;
use app\common\enum\Setting as SettingEnum;
use app\common\model\user\Application as Model;
use think\db\exception\DbException;
use think\Paginator;

class Application extends Model
{
    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $userId = UserService::getCurrentLoginUserId();

        // 查询列表记录
        $list = $query
            ->with(['job', 'subject_level'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->where('user_id', '=', $userId)
            ->order(['create_time' => 'desc'])
            ->select();
        $config = SettingModel::getItem(SettingEnum::H5HOME);
        if (!empty($config['class_hour'])) {
            $class_hour = (float)$config['class_hour'];
            foreach ($list as $item) {
                $lear = $class_hour - $item->accumulate_learn;
                $item->residueLearn = $lear > 0 ? $lear : '';
            }
        }
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',
        ]);
        $filter = [];
        !empty($params['search']) && $filter[] = ["subject_name", "like", "%{$params['search']}%"];
        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data)
    {
        $userId = UserService::getCurrentLoginUserId();

        $data['user_id'] = $userId;
        $data['store_id'] = self::$storeId;
        return $this->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        return $this->save($data);
    }
}
